package com.wanxi.util;

import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

public class CodeFlashFilter implements HandlerInterceptor {
    List<String> list = new ArrayList<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String remoteAddr = request.getRemoteAddr();

        synchronized (list) {
            if (list.contains(remoteAddr)) {
                return false;
            } else {
                list.add(remoteAddr);
                deleteObject(list, remoteAddr);
            }
        }
        //判断为5s后，放行
        return true;
    }

    private void deleteObject(List list, String ip) {
        Thread thread = new Thread(() -> {
            synchronized (ip) {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                list.remove(ip);
            }
        });
        thread.start();
    }
}
